package zhongbo.java.air.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import zhongbo.java.air.common.constants.AirConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年03月29日 星期六 16:02:30
 */
public class HttpServletUtil {

    /**
     * 任意地方获取request
     *
     * @return Request
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest();
        }
        throw new RuntimeException("获取Request对象异常, null");
    }

    /**
     * 从请求头获取token
     *
     * @return token令牌
     */
    public static String getHeaderToken() {
        return getRequest().getHeader(AirConstants.authHeader);
    }

    /**
     * 从headerToken获取用户名
     *
     * @return 用户名
     */
    public static String getUserNameFromToken() {
        try {
            String headerToken = HttpServletUtil.getHeaderToken();
            Jws<Claims> claimsJws = JwtUtil.parseToken(headerToken);
            Claims body = claimsJws.getBody();
            return body.get("userName", String.class);
        } catch (Exception ignore) {
        }
        return "";
    }
}
